<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme

export default {
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    unit: {
      type: String,
      default: "台",
    },
    dataName: {
      type: String,
      default: "台",
    },
    xAxisData: {
      type: Array,
      default: () => []
    },
    seriesData: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    xAxisData: {
      handler() {
        this.updateChart();
      },
      deep: true
    },
    seriesData: {
      handler() {
        this.updateChart();
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");
      this.updateChart();
    },
    updateChart() {
      this.chart.setOption({
        legend: {
          textStyle: {
            color: "#ffffff",
          },
          right: 0,
          itemHeight: 5,
          itemWidth: 20,
          backgroundColor: "#0AA7FF4D",
        },
        grid: {
          top: 30,
          left: 40,
          right: 0,
          bottom: 30,
        },
        xAxis: {
          type: "category",
          data: this.xAxisData,  // Use passed x-axis data
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          type: "value",
          splitLine: {
            lineStyle: {
              type: "dashed",
              color: "#B0D7FF33",
            },
          },
          name: `单位：${this.unit}`,
          nameTextStyle: {
            color: "#999999",
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        series: [
          {
            name: this.dataName,
            data: this.seriesData,  // Use passed y-axis data
            type: "pictorialBar",
            symbol: "rect",
            symbolRepeat: "fixed",
            symbolMargin: 5,
            symbolClip: true,
            symbolSize: [20, 10],
            itemStyle: {
              color: "#36F5F7",
            },
            z: 10,
          }
        ],
      });
    }
  },
};
</script>